package com.blb.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器端
 */
public class MyServer {

    //端口号
    public static final int PORT = 8888;

    public void start(){
        System.out.println("服务器启动了");
        //创建ServerSocket对象 try-with-resource 自动关闭对象
        try(ServerSocket serverSocket = new ServerSocket(PORT);) {
            while(true){
                //接收客户端连接
                Socket client = serverSocket.accept();
                System.out.println(client.getInetAddress() + "连接了");
                //获得客户端的输入流，读取消息
                try(ObjectInputStream inputStream = new ObjectInputStream(
                        client.getInputStream())) {
                    String message = inputStream.readUTF();
                    System.out.println(client.getInetAddress() + "说：" + message);
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new MyServer().start();
    }
}
